package com.haitaoit.chengquan.module.car;

import android.app.Dialog;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.util.TypedValue;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.ScrollView;
import android.widget.TextView;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.haitaoit.chengquan.R;
import com.haitaoit.chengquan.base.BackCall;
import com.haitaoit.chengquan.base.ExitApplication;
import com.haitaoit.chengquan.module.car.activity.OrderSubmitActivity;
import com.haitaoit.chengquan.module.car.adapter.CarAdapter;
import com.haitaoit.chengquan.module.car.model.CarModel;
import com.haitaoit.chengquan.utils.Constant;
import com.haitaoit.chengquan.utils.DateTimeUtil;
import com.haitaoit.chengquan.utils.DialogUtil;
import com.haitaoit.chengquan.utils.GetSign;
import com.haitaoit.chengquan.utils.HttpUtilsSingle;
import com.haitaoit.chengquan.utils.NameValuePairSign;
import com.haitaoit.chengquan.utils.PreferenceUtils;
import com.haitaoit.chengquan.utils.ToastUtils;
import com.haitaoit.chengquan.utils.Utils;
import com.haitaoit.chengquan.view.PullToRefreshBase;
import com.haitaoit.chengquan.view.PullToRefreshScrollView;
import com.haitaoit.chengquan.view.swipemenulistview.SwipeMenu;
import com.haitaoit.chengquan.view.swipemenulistview.SwipeMenuCreator;
import com.haitaoit.chengquan.view.swipemenulistview.SwipeMenuItem;
import com.haitaoit.chengquan.view.swipemenulistview.SwipeMenuListView;
import com.lidroid.xutils.ViewUtils;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.RequestParams;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;
import com.lidroid.xutils.view.annotation.ViewInject;
import com.lidroid.xutils.view.annotation.event.OnClick;
import com.squareup.leakcanary.RefWatcher;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by Administrator on 2016/9/22.
 */
public class CarFragment extends Fragment implements PullToRefreshBase.OnRefreshListener<ScrollView> {
    @ViewInject(R.id.pullrefreshscrollview)
    PullToRefreshScrollView pullrefreshscrollview;
    @ViewInject(R.id.car_money)
    TextView car_money;
    @ViewInject(R.id.car_jiesuan)
    TextView car_jiesuan;

    private ScrollView mScrollView;
    private LinearLayout null_information_layout;
    private SwipeMenuListView listView;

    private boolean isFrist = true;
    private int page = 1;

    private CarAdapter adapter;
    private  List<CarModel> new_list = new ArrayList<CarModel>();;



    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View v = inflater.inflate(R.layout.fragment_car, null);
        ViewUtils.inject(this, v);


        View view = LayoutInflater.from(getActivity()).inflate(R.layout.scrollview_swipemenu_listview_layout, null);
        null_information_layout = (LinearLayout) view.findViewById(R.id.null_information_layout);
        listView = (SwipeMenuListView) view.findViewById(R.id.scrollview_swipemenu_listview);

        pullrefreshscrollview.setPullLoadEnabled(false);
        pullrefreshscrollview.setPullRefreshEnabled(false);
        pullrefreshscrollview.setOnRefreshListener(this);
        pullrefreshscrollview.setLastUpdatedLabel(DateTimeUtil
                .getFormatDateTime(DateTimeUtil.getCurrTimestamp()));
        mScrollView = pullrefreshscrollview.getRefreshableView();
        mScrollView.setFillViewport(true);
        mScrollView.setVerticalScrollBarEnabled(false);
        mScrollView.addView(view);

        adapter = new CarAdapter(getActivity());
        adapter.setBackCall(backCall);
        listView.setAdapter(adapter);
        listView.setMenuCreator(creator);
        listView.setOnMenuItemClickListener(MenuItemClickListener);




        car_money.setText("¥ 0");
        car_jiesuan.setText("结算（0）");

        return v;
    }

    @Override
    public void onResume() {
        super.onResume();
        //结算完后就应该刷新
        httpGetuser_cart_list();
    }

    @OnClick({R.id.car_jiesuan,})
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.car_jiesuan:// 结算
                if (adapter.getList() != null) {
                    String id = "";
                    for (int i = 0; i < adapter.getList().size(); i++) {
                        if (adapter.getList().get(i).isSelect()) {
                            id = id + adapter.getList().get(i).getId() + ",";
                        }
                    }
                    if (id.equals("")) {
                        ToastUtils.showToast("请选择商品！");
                    } else {
                        id = id.substring(0, id.length() - 1);
                        Intent intent = new Intent(getActivity(), OrderSubmitActivity.class);
                        intent.putExtra("type", "car");
                        intent.putExtra("id", id);
                        startActivity(intent);
                    }
                } else {
                    ToastUtils.showToast("购物车是空的哦！");
                }
                break;
        }
    }

    BackCall backCall = new BackCall() {
        @Override
        public void deal(int which, Object... obj) {
            Integer position = (Integer) obj[0];
            switch (which) {
                case R.id.car_cb:
                    Selectnum();
                    break;
                case R.id.car_jian:// 减
                    if (Integer.valueOf(adapter.getList().get(position).getAccessories_goods_count()) > 1) {
//                        adapter.getList().get(position).setAccessories_goods_count(
//                                (Integer.valueOf(adapter.getList().get(position).getAccessories_goods_count()) - 1) + "");
//                        adapter.notifyDataSetChanged();
                        httpGetupdate_user_cart(adapter.getList().get(position).getId(), position, "1", "2");
                    }
//                    Selectnum();
                    break;
                case R.id.car_jia:// 加
//                    if (Integer.valueOf(adapter.getList().get(position).getAccessories_goods_count())
//                            < Integer.valueOf(adapter.getList().get(position).getStock())) {
//                        adapter.getList().get(position).setAccessories_goods_count(
//                                (Integer.valueOf(adapter.getList().get(position).getAccessories_goods_count()) + 1) + "");
//                        adapter.notifyDataSetChanged();
                    httpGetupdate_user_cart(adapter.getList().get(position).getId(), position, "1", "1");
//                    }
//                    Selectnum();
                    break;
            }
            super.deal(which, obj);
        }
    };

    // 统计价格数量
    public void Selectnum() {
        float money = 0.00f;
        int num = 0;
        for (int i = 0; i < adapter.getList().size(); i++) {
            if (adapter.getList().get(i).isSelect()) {
                money = money + Float.valueOf(adapter.getList().get(i).getPrice()) *
                        Integer.valueOf(adapter.getList().get(i).getAccessories_goods_count());
                num = num + Integer.valueOf(adapter.getList().get(i).getAccessories_goods_count());
            }
        }
        car_money.setText("¥ " + Utils.format(money));
        car_jiesuan.setText("结算（" + num + "）");
    }

    //添加滑动菜单
    SwipeMenuCreator creator = new SwipeMenuCreator() {
        @Override
        public void create(SwipeMenu menu) {
            switch (menu.getViewType()) {
                case 0:
                    createMenu1(menu);
                    break;
            }
        }
    };

    private void createMenu1(SwipeMenu menu) {
        SwipeMenuItem delItem = new SwipeMenuItem(getActivity());
        delItem.setBackground(R.color.red);
        delItem.setWidth(dp2px(60));
        delItem.setTitle("删除");
        delItem.setTitleColor(getResources().getColor(R.color.white));
        delItem.setTitleSize(16);
        menu.addMenuItem(delItem);
    }

    //滑动菜单点击事件
    SwipeMenuListView.OnMenuItemClickListener MenuItemClickListener = new SwipeMenuListView.OnMenuItemClickListener() {
        @Override
        public boolean onMenuItemClick(final int position, SwipeMenu menu, final int index) {
            switch (index) {
                case 0://删除
                    Dialog dlg = DialogUtil.showInfoDialog1(getActivity(), "温馨提示", "是否确认删除?", "是", "否", new BackCall() {
                        public void deal(int which, Object... obj) {
                            switch (which) {
                                case R.id.confirm:// 确定
                                    httpGetdel_user_cart(adapter.getList().get(position).getId());
                                    break;
                            }
                            super.deal(which);
                        }
                    });
                    dlg.setCanceledOnTouchOutside(true);
                    dlg.show();
                    break;
            }
            return false;
        }
    };

    // 列表
    private void httpGetuser_cart_list() {
        List<NameValuePairSign> list = new ArrayList<NameValuePairSign>();
        list.add(new NameValuePairSign("user_id", PreferenceUtils.getPrefString("user_id", "")));
        String sign = GetSign.genPackageSign(list);

        RequestParams params = new RequestParams();
        params.addQueryStringParameter("user_id", PreferenceUtils.getPrefString("user_id", ""));
        params.addQueryStringParameter("sign", sign);


        HttpUtilsSingle.doGet(getActivity(), false, Constant.Getuser_cart_list, params, new RequestCallBack<String>() {
            @Override
            public void onSuccess(ResponseInfo<String> arg0) {
                String result = arg0.result.toString();

                try {
                    JSONObject json = new JSONObject(result);
                    String Errcode = json.getString("ErrCode");
                    String Errmsg = json.getString("ErrMsg");
                    String Response = json.getString("Response");
                    Gson gson = new Gson();
                    switch (Integer.valueOf(Errcode)) {
                        case 1:// 失败
                            ToastUtils.showToast(Errmsg);
                            if (Errmsg.equals("未找到用户")) {
                                /*PreferenceUtils.setPrefString("user_id", "");
                                PreferenceUtils.setPrefString("account_type", "");
                                Intent intent = new Intent(getActivity(), LoginActivity.class);
                                intent.putExtra("tag", "2");
                                startActivity(intent);*/
                                return;
                            }
                            break;
                        case 0:// 成功
                            new_list = gson.fromJson(Response,
                                    new TypeToken<List<CarModel>>() {
                                    }.getType());

                            break;
                        case 2:
//                            ToastUtils.showToast(Errmsg);
                            break;
                    }
                    //在获取成功后才进行刷新adapter
                    if (isNullDate(new_list)) {
                        adapter.setList(new_list);
                        adapter.notifyDataSetChanged();
                        Selectnum();
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onFailure(HttpException arg0, String arg1) {
                ToastUtils.showToast("获取数据失败,请检查网络");
            }
        });
    }

    // 购物车数量修改
    private void httpGetupdate_user_cart(String id, final int position, String number, final String type) {
        List<NameValuePairSign> list = new ArrayList<NameValuePairSign>();
        list.add(new NameValuePairSign("user_id", PreferenceUtils.getPrefString("user_id", "")));
        list.add(new NameValuePairSign("id", id));
        list.add(new NameValuePairSign("number", number));
//        list.add(new NameValuePairSign("type", type));
        String sign = GetSign.genPackageSign(list);

        RequestParams params = new RequestParams();
        params.addQueryStringParameter("user_id", PreferenceUtils.getPrefString("user_id", ""));
        params.addQueryStringParameter("id", id);
        params.addQueryStringParameter("number", number);
//        params.addQueryStringParameter("type", type);
        params.addQueryStringParameter("sign", sign);

        HttpUtilsSingle.doGet(getActivity(), false, Constant.Getupdate_user_cart, params, new RequestCallBack<String>() {
            @Override
            public void onSuccess(ResponseInfo<String> arg0) {
                String result = arg0.result.toString();
                try {
                    JSONObject json = new JSONObject(result);
                    String Errcode = json.getString("ErrCode");
                    String Errmsg = json.getString("ErrMsg");
                    String Response = json.getString("Response");
                    switch (Integer.valueOf(Errcode)) {
                        case 1:// 失败
                            ToastUtils.showToast(Errmsg);
                            break;
                        case 0:// 成功
                            if (type.equals("1")) {// 加
                                adapter.getList().get(position).setAccessories_goods_count(
                                        (Integer.valueOf(adapter.getList().get(position).getAccessories_goods_count()) + 1) + "");
                            } else if (type.equals("2")) {// 减
                                adapter.getList().get(position).setAccessories_goods_count(
                                        (Integer.valueOf(adapter.getList().get(position).getAccessories_goods_count()) - 1) + "");
                            }
                            adapter.notifyDataSetChanged();
                            Selectnum();
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onFailure(HttpException arg0, String arg1) {
                ToastUtils.showToast("获取数据失败,请检查网络");
            }
        });
    }

    // 删除
    private void httpGetdel_user_cart(String id) {
        List<NameValuePairSign> list = new ArrayList<NameValuePairSign>();
        list.add(new NameValuePairSign("user_id", PreferenceUtils.getPrefString("user_id", "")));
        list.add(new NameValuePairSign("cart_id", id));
        String sign = GetSign.genPackageSign(list);

        RequestParams params = new RequestParams();
        params.addQueryStringParameter("user_id", PreferenceUtils.getPrefString("user_id", ""));
        params.addQueryStringParameter("cart_id", id);
        params.addQueryStringParameter("sign", sign);

        HttpUtilsSingle.doGet(getActivity(), false, Constant.Getdel_user_cart, params, new RequestCallBack<String>() {
            @Override
            public void onSuccess(ResponseInfo<String> arg0) {
                String result = arg0.result.toString();
                try {
                    JSONObject json = new JSONObject(result);
                    String Errcode = json.getString("ErrCode");
                    String Errmsg = json.getString("ErrMsg");
                    String Response = json.getString("Response");
                    switch (Integer.valueOf(Errcode)) {
                        case 1:// 失败
                            ToastUtils.showToast(Errmsg);
                            break;
                        case 0:// 成功
                            ToastUtils.showToast(Errmsg);
                            httpGetuser_cart_list();
                            break;
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onFailure(HttpException arg0, String arg1) {
                ToastUtils.showToast("获取数据失败,请检查网络");
            }
        });
    }

    private int dp2px(int dp) {
        return (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP,
                dp, getResources().getDisplayMetrics());
    }

    /**
     * @tab 判断listview是否有值
     */
    private boolean isNullDate(List<CarModel> rewordList) {
        if (rewordList == null || rewordList.size() == 0) {
            null_information_layout.setVisibility(View.VISIBLE);
            listView.setVisibility(View.GONE);
            return false;
        } else {
            null_information_layout.setVisibility(View.GONE);
            listView.setVisibility(View.VISIBLE);
            return true;
        }
    }

    @Override
    public void onPullDownToRefresh(PullToRefreshBase<ScrollView> refreshView) {
        pullrefreshscrollview.setLastUpdatedLabel(DateTimeUtil
                .getFormatDateTime(DateTimeUtil.getCurrTimestamp()));
        isFrist = true;
        page = 1;
    }

    @Override
    public void onPullUpToRefresh(PullToRefreshBase<ScrollView> refreshView) {
        pullrefreshscrollview.setLastUpdatedLabel(DateTimeUtil
                .getFormatDateTime(DateTimeUtil.getCurrTimestamp()));
        isFrist = false;
        page++;
    }

    //主要用于检测内存泄漏
    @Override
    public void onDestroy() {
        super.onDestroy();
        RefWatcher refWatcher = ExitApplication.getRefWatcher(getActivity());
        refWatcher.watch(this);
    }
}
